package com.xiaoxx.annotation;

import com.xiaoxx.common.base.JwtUser;
import com.xiaoxx.common.error.ErrorException;
import com.xiaoxx.common.result.RType;
import com.xiaoxx.model.entity.sys.SysRole;
import com.xiaoxx.service.SysRoleService;
import com.xiaoxx.utils.JwtUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author :HX
 * @date : 2023/8/2
 * 日志拦截器
 */
@Aspect
@Component
public class AuthManageImpl {
    @Resource
    private HttpServletRequest request;

    @Resource
    private SysRoleService roleService;

    @Pointcut("@annotation(com.xiaoxx.annotation.AuthManage)")
    public void AuthManagePointcut() {
    }

    @Around(value = "AuthManagePointcut()")
    public Object authManage(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取拦截方法名称
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        AuthManage authManage = methodSignature.getMethod().getDeclaredAnnotation(AuthManage.class);
        JwtUser jwtUser = JwtUtil.getJwtUser(request);
        SysRole sysRole = roleService.getRoleNameByUserId(jwtUser.getUserId());
        if (sysRole == null) {
            throw new ErrorException(RType.NOT_AUTH);
        }
        if (!Arrays.asList(authManage.roles()).contains(sysRole.getCode())) {
            throw new ErrorException(RType.NOT_AUTH);
        }
        return joinPoint.proceed();
    }


    /**
     * @author HX
     * @create 2022/3/1 14:29
     * @desc 获取ip
     **/
    private String getIpAddress(HttpServletRequest request) {
        String unknown = "unknown";
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
